package com.creditease.mobile.news.util;

import android.os.AsyncTask;
import com.creditease.mobile.news.db.DBUtils;
import com.creditease.mobile.news.db.NewsSQLiteOpenHelper;
import com.creditease.mobile.news.model.ImgModel;
import com.creditease.mobile.news.model.NewsModel;
import com.creditease.mobile.news.services.NewsServices;
import com.creditease.mobile.news.ui.NewsHomeActivity;
import com.creditease.mobile.rss.RssConst;
import com.creditease.mobile.util.FileUtil;
import com.creditease.mobile.vo.NewsDetail;
import com.creditease.mobile.vo.TopVo;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class NewsDownloadTask extends AsyncTask<Object, Void, Boolean> {
    private String TAG = NewsDownloadTask.class.getName();

    @SuppressWarnings(value = "ALL")
    @Override
    protected Boolean doInBackground(Object... objs) {
        NewsSQLiteOpenHelper dbHelper = (NewsSQLiteOpenHelper) objs[0];
        List<TopVo> list = (List<TopVo>) objs[1];
        NewsHomeActivity home = (NewsHomeActivity) objs[2];
        NewsServices ns = new NewsServices();
        for (TopVo rs : list) {
            String cid = rs.cid;
            //                 取消

            try {
                //List<NewsModel> list2 = DBUtils.getDataFromNewsListTable(dbHelper.getWritableDatabase(), rs.cid, 0, 20);
                List<NewsModel> list2 = ns.getRemoteData(cid, 0, 20, dbHelper);
                dbHelper.deleImg(cid);
                int i = 0;
                for (NewsModel news : list2) {
                    dbHelper.insertDataToNewsListTable(cid, news.docid,
                            news.imgsrc, news.digest, news.replyCount, news.url, news.title,
                            news.lmodify, news.subtitle, "false", "false", news.hasImg,
                            "false", (i++) + "", "", "");
                }

                List<NewsDetail> newsList = DBUtils.getDatasFromNewsTable(dbHelper.getWritableDatabase(), cid);

                Set<String> newsIds = new HashSet<String>();
                for (NewsDetail model : newsList) {
                    newsIds.add(model.docId);
                }
                home.reflushCallBack(false, "true", cid);
                for (NewsModel news : list2) {
                    String newsId = news.docid;

                    if (!newsIds.contains(newsId)) {
                        ns.getRemoteNewsDetail(cid, newsId, dbHelper,true);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                home.reflushCallBack(false, "false", cid);
            }
        }

        return false;
    }
}
